"use strict";
/**
 * 发送模板消息服务
 * Created by liamjung on 2018/6/28.
 */
const AbstractService = require("../abstract_service");
const {getMpConfig} = require("@libfintech/api-gateway-core/util/util");

class TemplateService extends AbstractService {

    /**
     * 执行
     * @param dto       TemplateDTO
     * @param mpConfig  公众号配置
     * @param pipeline  管道
     * @returns {Promise.<void>}
     */
    async execute(dto, mpConfig, pipeline) {

        let templateId = super.getTemplateId(mpConfig, dto.type);

        let data = {};
        for (let d of dto.data) {
            data[d.name] = {
                value: d.value,
                color: d.color
            };
        }

        let url = this.oauth2buildAuthorizationUrl(dto.url, "snsapi_base", "STATE");

        let miniProgram;
        let miniProgramId = dto.miniProgramId;

        if (miniProgramId) {

            let miniProgramConfig = await getMpConfig.call(global, miniProgramId);

            if (!miniProgramConfig) {
                //配置不存在时，抛出异常

                pipeline.logger.warn("There is no mini program (mpId: " + miniProgramId + ") config");

                throw new ResponseError(404, undefined, "小程序配置不存在");
            }

            miniProgram = {
                appid: miniProgramConfig.appId,
                pagepath: dto.pagePath
            };
        }

        let bodyJson = {
            touser: dto.openId,
            template_id: templateId,
            url: url,
            miniprogram: miniProgram,
            // color: topColor,
            data: data
        };

        super.updateRequest(pipeline.request, undefined, bodyJson);
    }
}

module.exports = new TemplateService();